package my;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.util.ArrayList;
import java.util.Arrays;

public class FileMerge {

	  public static final int BUFSIZE = 1024 * 8;
	    @SuppressWarnings("resource")
//outFile合并后的内容要存入的文件，files目标文件集（文件合并的方法）
	    public static void mergeFiles(String outFile, String[] files) {
	        FileChannel outChannel = null;
	        System.out.println("Merge " + Arrays.toString(files) + " into " + outFile);
	        try {
	            outChannel = new FileOutputStream(outFile).getChannel();
	            for (String f : files) {
	                Charset charset = Charset.forName("utf-8");
	                CharsetDecoder chdecoder = charset.newDecoder();
	                CharsetEncoder chencoder = charset.newEncoder();
	                FileChannel fc = new FileInputStream(f).getChannel();
	                ByteBuffer bb = ByteBuffer.allocate(BUFSIZE);
	                CharBuffer charBuffer = chdecoder.decode(bb);
	                ByteBuffer nbuBuffer = chencoder.encode(charBuffer);
	                while (fc.read(nbuBuffer) != -1) {
	                    bb.flip();
	                    nbuBuffer.flip();
	                    outChannel.write(nbuBuffer);
	                    bb.clear();
	                    nbuBuffer.clear();
	                }
	                fc.close();
	            }
	            System.out.println("Merged!! ");
	        } catch (IOException ioe) {
	            ioe.printStackTrace();
	        } finally {
	            try {
	                if (outChannel != null) {
	                    outChannel.close();
	                }
	            } catch (IOException ignore) {
	            }
	        }
	    }

	    public static void main(String[] args) {            //main方法
	        String sourceDir = "d:\\myfile\\";
	        File[] file = (new File(sourceDir)).listFiles();        //获取文件夹sourceDir下所有文件
	        //String[] result=new String[]{file.toString()};
	        //file=file.toString();
	        ArrayList<String> list = new ArrayList<String>();    //String类型的数组
	        String [] strs = new String[file.length];            //可以定义动态的String数组
	        for (int i = 0; i < file.length; i++) {
//	            list.add(sourceDir + file[i].getName());
	            strs[i] = sourceDir + file[i].getName();        //将信息存入文件的String数组    
	        }
	        /*for (int i = 0; i < strs.length; i++) {            //验证，数组能否正常输出
	            //System.out.println(strs[i]);    
	        }*/
//	        list.toArray();
	        mergeFiles("d:\\606_177052856.lst", strs);//将strs中文件集合到G:\\finish\\zy141230\\606_177052856.lst文件中
	    }

}
